﻿using JYH.Business;
using JYH.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Hosting;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
using FastReport.Utils;
using FastReport.Web;
using FastReport.Export.Image;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using JYH.Framework;

namespace JYH.Web.MES.Controllers
{
    public class FastReportController : ApiController
    {
        /// <summary>
        /// 根据产品ID获取报告，并根据查询参数导出为指定格式。
        /// </summary>
        /// <param name="query">从URI获取的查询参数，包含导出格式和其他参数。</param>
        /// <returns>返回一个HttpResponseMessage对象，包含报告数据或错误信息。</returns>
        [HttpPost]
        public HttpResponseMessage GetReportById([FromBody] dynamic query)
        {
            // 查找客户的报告
            //Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id);
            string Msg = "";
            BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();
            //SalPartnerLableBLL lableBLL = new SalPartnerLableBLL();
            //MfgWorkOrderBarcodeBLL barcodeBLL = new MfgWorkOrderBarcodeBLL();
            string printQty = query.printQty;
            string Ids = query.CodeID;
            SysParaInfo paraInfo = new SysParaInfo();
            paraInfo = SysParaInfoBLL.GetParaInfo("MaterialBarcode", out Msg);
            string BarcodeLable = "MaterialBarcode";
            if (paraInfo != null)
            {
                BarcodeLable = paraInfo.ParaValue;
            }

            DataSet dataSet = new DataSet();
            // 获取数据源
            dataSet = bll.GetWmsBarCodeInfo(Ids, printQty, out Msg);
            if (dataSet != null && dataSet.Tables[0] != null)
            {
                dataSet.Tables[0].TableName = "BasBarcodeInfo";
            }
            // 文件地址
            string reportPath = HostingEnvironment.MapPath("~/App_Data/Lable/" + BarcodeLable + ".frx");
            // 创建内存流以存储报告数据
            MemoryStream stream = new MemoryStream();

            try
            {
                // 启用FastReport的Web模式
                Config.WebMode = true;

                using (WebReport report = new WebReport())
                {
                    // 加载报告
                    report.Report.Load(reportPath);
                    //注入到报告
                    report.RegisterData(dataSet);
                    report.Report.Dictionary.Connections[0].ConnectionString = ConfigHelper.GetConnectionString("DBCONN");
                    report.Refresh();
                    //启动当前数据源
                    //report.Report.GetDataSource(dataSet.Tables[0].TableName).Enabled = true;
                    report.Report.Prepare(); // 确保数据准备完成
                    report.InlineRegistration = true;
                    report.Width = Unit.Percentage(650);
                    report.Height = Unit.Percentage(450);
                    // 根据查询参数导出报告
                    if (query.Format == "png")
                    {
                        // 导出报告为PNG格式
                        using (ImageExport img = new ImageExport())
                        {
                            img.ImageFormat = ImageExportFormat.Png;
                            img.SeparateFiles = false;
                            img.ResolutionX = 96;
                            img.ResolutionY = 96;
                            report.Report.Export(img, stream);
                            query.Format = "png";
                            byte[] streamArray = Encoding.UTF8.GetBytes(img.ToString());
                            stream.Write(streamArray, 0, streamArray.Length);
                        }
                    }
                    else
                    {
                        // 导出报告为HTML格式
                        HtmlString reportHtml = report.GetHtml();
                        byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString());
                        stream.Write(streamArray, 0, streamArray.Length);
                    }
                }
                // 创建HTTP响应消息
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };

                // 释放内存流
                stream.Dispose();
                string mat = query.Format;
                if (!string.IsNullOrEmpty(mat))
                {
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + mat);
                }
                else
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/html");

                return result;
            }
            catch
            {
                // 捕获异常并返回内部服务器错误
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
        }

        /// <summary>
        /// 库位打印。
        /// </summary>
        /// <param name="WorkOrderID">报告的唯一标识符。</param>
        /// <param name="query">从URI获取的查询参数，包含导出格式和其他参数。</param>
        /// <returns>返回一个HttpResponseMessage对象，包含报告数据或错误信息。</returns>
        [HttpPost]
        public HttpResponseMessage GetReportStrById([FromBody] dynamic query)
        {
            // 查找客户的报告
            //Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id);
            string Msg = "";
            string Ids = query.CodeID;
            string WarehouseID = query.WarehouseID;
            DataSet dataSet = new DataSet();
            BasStorageInfoBLL bll = new BasStorageInfoBLL();
            // 获取数据源
            dataSet = bll.GetStRInfos(WarehouseID, Ids, out Msg);
            if (dataSet != null && dataSet.Tables[0] != null)
            {
                dataSet.Tables[0].TableName = "BasStorageInfo";
            }
            SysParaInfo paraInfo = new SysParaInfo();
            paraInfo = SysParaInfoBLL.GetParaInfo("StorageNO", out Msg);
            string BarcodeLable = "MaterialBarcode";
            if (paraInfo != null)
            {
                BarcodeLable = paraInfo.ParaValue;
            }
            // 文件地址
            string reportPath = HostingEnvironment.MapPath("~/App_Data/Lable/" + BarcodeLable + ".frx");
            // 创建内存流以存储报告数据
            MemoryStream stream = new MemoryStream();
            try
            {
                // 启用FastReport的Web模式
                Config.WebMode = true;

                using (WebReport report = new WebReport())
                {
                    // 加载报告
                    report.Report.Load(reportPath);
                    //注入到报告
                    report.RegisterData(dataSet);
                    report.Report.Dictionary.Connections[0].ConnectionString = ConfigHelper.GetConnectionString("DBCONN");
                    report.Refresh();
                    //启动当前数据源
                    //report.Report.GetDataSource(dataSet.Tables[0].TableName).Enabled = true;
                    report.Report.Prepare(); // 确保数据准备完成
                    report.InlineRegistration = true;
                    report.Width = Unit.Percentage(650);
                    report.Height = Unit.Percentage(450);
                    // 根据查询参数导出报告
                    if (query.Format == "png")
                    {
                        // 导出报告为PNG格式
                        using (ImageExport img = new ImageExport())
                        {
                            img.ImageFormat = ImageExportFormat.Png;
                            img.SeparateFiles = false;
                            img.ResolutionX = 96;
                            img.ResolutionY = 96;
                            report.Report.Export(img, stream);
                            query.Format = "png";
                            byte[] streamArray = Encoding.UTF8.GetBytes(img.ToString());
                            stream.Write(streamArray, 0, streamArray.Length);
                        }
                    }
                    else
                    {
                        // 导出报告为HTML格式
                        HtmlString reportHtml = report.GetHtml();
                        byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString());
                        stream.Write(streamArray, 0, streamArray.Length);
                    }
                }
                // 创建HTTP响应消息
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };

                // 释放内存流
                stream.Dispose();
                string mat = query.Format;
                if (!string.IsNullOrEmpty(mat))
                {
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + mat);
                }
                else
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/html");

                return result;
            }
            catch
            {
                // 捕获异常并返回内部服务器错误
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
        }
    }
}